<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\facade\Sms;
use app\common\facade\WeChatMini;
use app\common\model\Ad;
use app\common\model\Product as ProductModel;
use app\common\tool\Result;
use think\facade\Cache;
use think\Response;

class Index extends Base
{
    public function index(): Response
    {
        return Result::fail('访问无效');
    }

    public function ad(): Response
    {
        $ad = Ad::where('id',1)->where('status', 1)->field('id,title,link_type,image,link_id')->find();
        return Result::success('success', $ad);
    }

    /**
     * 协议
     */
    public function communal(): Response
    {
        $type = $this->request->get('type');
        $result['communal'] = handleRichText(Cache::get('system')[$type]);

        return Result::success('success', $result);
    }

    /**
     * 小程序审核开关
     */
    public function appletOpen(): Response
    {
        $result = Cache::get('system')['applet_open'];

        return Result::success('success', $result);
    }

    /**
     * 发送短信验证码
     * @return Response
     */
    public function sendSms(): Response
    {
        try{
            $param = $this->request->param();
            $this->validate($param, 'Sms');
            $mobile = $param['mobile'];

            $code = rand(100000, 999999);
            Cache::set('yusheng250124:'.$mobile, $code, 300);

            $content = "验证码是:{$code}（裕生平台验证码，5分钟内有效）";
            Sms::send($mobile,$content);

            return Result::success('发送成功');
        }catch (\Exception $e){
            return Result::fail('服务器错误');
        }

    }

    /**
     * 乡村振兴太阳码
     * @return Response
     */
    public function villageCode()
    {
        $scene = "village_code_".date("YmdHis").mt_rand(1000,9999);
        $savePath = '/uploads/productQrcode/';
        $code = WeChatMini::getMiniScene($scene, 'package-country/home/home', $savePath);

        if($code){
            return Result::success('success', ['code'=>$code]);
        }else{
            return Result::fail('获取太阳码失败');
        }
    }
}
